<template>
  <a-card :bordered="false">
    <a-modal :visible="visibleImport" @cancel="() => { this.visibleImport = false; }">
      <a-upload
        name="file"
        :multiple="false"
        :showUploadList="false"
        :action="$rootUrl + leading"
        @change="handleChange"
        style="display: inline-block"
        accept=".xlsx,.xls"
        :headers="headers"
        class="upload-list-inline"
        >
        <a-button type="primary">
          <a-icon type="upload" />
          上传Excel数据
        </a-button>
      </a-upload>
      <template slot="footer">
        <a-button @click="() => { this.visibleImport = false; }">关闭</a-button>
      </template>
    </a-modal>
    <div class="table-operator" style="display: flex;justify-content: space-between;">
      <div>
          <a-button type="primary" icon="download" @click="downloadTemplate">下载模板</a-button>
          <a-button type="primary" icon="upload" @click="handleImport()">导入</a-button>
          <!-- <a-button v-if="hasPerm('TaxMaterials.Add')" type="primary" icon="plus" @click="handleAdd()">新增</a-button> -->
        </div>
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="24" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="BusStoreName">业务仓库</a-select-option>
                <a-select-option key="FinStoreName">财务仓库</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" @keydown.enter="getDataList" />
            </a-form-item>
            <a-form-item>

              <a-button
                type="primary"
                @click="() => {
                  this.pagination.current = 1
                  this.getDataList()
                }
                ">查询
              </a-button>
              <a-button style="margin-left: 8px" @click="; (queryParam = { condition: 'BusStoreName' });getDataList()">重置
                
              </a-button>
              <a-button
               v-if="hasPerm('cfg_compare_store.Add')"
                    type="primary"
                    @click="handleAdd">新增
                    
                  </a-button>
                   <a-button

                   v-if="hasPerm('cfg_compare_store.Delete')"
                        :disabled="selectedRowKeys.length <= 0"
                        type="primary"
                        @click="handleDelete('all')">删除
                    
                      </a-button>
            </a-form-item>

          </a-col>
        </a-row>
      </a-form>
      <!-- <a-button type="primary" icon="download" @click="downloadTemplate">下载模板</a-button> -->
      <!-- <a-button type="primary" icon="upload" @click="handleImport()">导入</a-button> -->
    </div>
    <div class="table-page-search-wrapper">
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 'calc(100vh - 330px)' }"
      :columns="columns"
      :rowKey="(row) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small">
      <span slot="TaxRate" slot-scope="text,scope">{{ text.substr(0,text.length-1) }}</span>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD') }}</span>
      <span slot="IsTax" slot-scope="text, record">
        <template>
          <a-tag :color="record.IsTax ? 'blue' : 'orange'">{{ record.IsTax ? '是' : '否' }}</a-tag>
        </template>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <!-- <a @click="handleAssociation(record.code)">关联税务目录</a> -->
          <a v-if="hasPerm('cfg_compare_store.Edit')" @click="handleEdit(record)">修改</a>
          <!-- <a-divider v-if="hasPerm('cfg_compare_store.Edit')" type="vertical" />
          <a @click="handleAssociationOut(record)">关联税务目录</a> -->
           <a-divider v-if="hasPerm('cfg_compare_store.Delete')" type="vertical" />
            <a v-if="hasPerm('cfg_compare_store.Delete')" @click="handleDelete(record.Id)">删除</a>
          <!-- <a v-if="hasPerm('Base_District.Edit')" @click="handleEdit(record.Id)">设置单价</a> -->
        </template>
      </span>
    </a-table>
  
    <edit-form ref="editForm" :parentObj="this"></edit-form>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import Token from '@/utils/cache/TokenCache'

const columns = [
  { title: '业务仓库ID', dataIndex: 'BusStoreId' },
  { title: '财务仓库ID', dataIndex: 'FinStoreId' },
  { title: '业务仓库', dataIndex: 'BusStoreName' },
  { title: '财务仓库', dataIndex: 'FinStoreName' },
  {
    title: '操作',
    key: 'action',
    width: '100px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: {
    EditForm
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true) + 24
    })
    this.getDataList()
  },
  data () {
    return {
      leading: '/Cfg/cfg_compare_store/Import',
      tableHeight: 570, // 表格高度
      data: [],
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      // 第一层drawer
      pagination1: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      // 第二层drawer
      pagination2: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      submitDisabled: true,
      filters1: {},
      filters2: {},
      sorter: { field: 'Id', order: 'desc' },
      loading: false,
      columns,
      queryParam: {
        condition: 'BusStoreName'
      },
      visible: false, // 关联税务目录弹框
      productsData: [], // 税务产品
      visiblees: false, // 第二层drawer
      beforeAssociation: [{ code: 1, name: 2, specification: 3 }], // 第一层数据，已关联
      association: [{ code: 11, name: 22, specification: 33 }], // 第二层数据，关联
      loading1: false, // 第一层drawer
      loading2: false, // 第一层drawer
      selectedRowKeys: [], // 最外层关联的选择框
      selectedRowKeys1: [], // 第二层关联选择框
      cInvCode: '', // 产品信息行列表code
      selectedRows: [],
      allData: [],
      TaxValue: '',
      visibleImport: false,
      visibleSetPrice: false,
      setPrice: '',
      setPriceId: '',
      TaxList: [],
      isAll: false,
      TaxRate: '',
      IsTax: 0,
      saveObj: {},
      disabled: false,
      headers: {
        authorization: 'Bearer ' + Token.getToken()
      },
    }
  },
  methods: {
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    handleTableChange1 (pagination, filters, sorter) {
      console.log(pagination)
      this.pagination1 = { ...pagination }
      this.filters1 = { ...filters }
      this.handleAssociation()
    },
    handleTableChange2 (pagination, filters, sorter) {
      this.pagination2 = { ...pagination }
      this.filters2 = { ...filters }
      this.handleAddS()
      if (JSON.parse(localStorage.getItem('CHECK-BOX')) && JSON.parse(localStorage.getItem('CHECK-BOX')).length > 0) {
        this.selectedRowKeys1 = JSON.parse(localStorage.getItem('CHECK-BOX'))
      }
    },
    handleOpenChoose () {
      this.handleAddS('1')
    },
    //新增
    handleAdd(){
      this.$refs.editForm.openForm(null,'新增单位对照表')
    },
    handleEdit(record) {
      this.$refs.editForm.openForm(record.Id, '编辑单位对照表')
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/Cfg/cfg_compare_store/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters1
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          this.data.forEach(item => {
            item.TaxRate = item.TaxRate ? item.TaxRate += '%' : ''
            item.TaxUnitPrice = this.$options.filters.NumberFormatss(item.TaxUnitPrice)
          })
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    handleAssociationOut (record) {
      this.TaxValue = ''
      this.setPrice = ''
      this.IsTax = 0
      this.TaxRate = ''
      this.saveObj = {
        Id: record.TaxId,
        TM_Code: record.TmCode,
        TM_TaxCode: record.TaxCode
      }
      if (record == 'all') {
        this.isAll = true
      } else {
        this.isAll = false
        this.IsTax = record.IsTax
        this.setPrice = record.TaxUnitPrice
        this.TaxValue = record.TaxName
        this.TaxRate = record.TaxRate.replace('%', '')
        this.setPriceId = record.code
      }
      this.visibleSetPrice = true
    },
    onChange (e) {
      console.log(e)
      this.IsTax = e.target.checked ? 1 : 0
    },
    // 导入文件类型
    handleChange (info) {
      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          this.$message.error(`${info.file.name}文件,${info.file.response.Msg},请检查文件内容！ `)
        } else {
          this.$message.success(`${info.file.name}  文件上传成功！`)
          this.getDataList()
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    setMon () {
      if (isNaN(this.setPrice * 1)) {
        this.setPrice = ''
        return
      }
      if (isNaN(this.setPrice * 1)) {
        this.setPrice = parseFloat(this.setPrice)
      }
      const reg = /^\d+(\.\d{0,8})?$/
      let flag2 = false
      if (!reg.test(this.setPrice)) {
        flag2 = true
      }
      if (flag2) {
        this.$message.warning('请输入正确的价格，最多八位小数')
      }
    },
    handleOk () {
      if (!this.TaxValue) {
        this.$message.error('请选择税务目录')
        return
      } else if (!this.setPrice) {
        this.$message.error('请选择输入单价')
        return
      } else if (!this.TaxRate) {
        this.$message.error('请选择输入税率')
        return
      }
      const reg = /^\d+(\.\d{0,8})?$/
      let flag2 = false
      if (!reg.test(this.setPrice)) {
        flag2 = true
      }
      if (flag2) {
        this.$message.warning('请输入正确的价格，最多八位小数')
        return
      }
      const arr = this.isAll ? this.selectedRowKeys : [this.setPriceId]
      this.$http.post('/MaterialManagement/cfg_compare_store/ProductTaxCorrelation', {
        'CInvCodes': arr,
        'TaxId': this.saveObj.Id,
        'TM_Code': this.saveObj.TM_Code || this.saveObj.TmCode,
        'TM_TaxCode': this.saveObj.TM_TaxCode,
        'TM_UnitPrice': Number(this.setPrice),
        'IsTax': this.IsTax,
        'TaxRate': Number(this.TaxRate)
      }).then(res => {
        if (res.Success) {
          this.$message.success('关联成功!')
          this.getDataList()
          this.handleCancel()
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    // 删除已关联
    handleDeleteAssociation (id) {
      const thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http.post('/MaterialManagement/TaxMaterialsRelation/DeleteData', [id]).then((resJson) => {
            resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.handleAssociation()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
    },
    handleCancel () {
      this.visibleSetPrice = false
      this.selectedRowKeys1 = []
      this.TaxList = []
      this.setPrice = ''
    },
    // 关联选择
    onSelectChange1 (selectedRowKeys, selectRows, id) {
      // console.log(selectedRowKeys, selectRows)
      this.selectedRowKeys1 = selectedRowKeys

      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('CHECK-BOX'))) {
        localStorage.setItem('CHECK-BOX', JSON.stringify(selectedRowKeys))
      } else {
        // 反则push
        const select = JSON.parse(localStorage.getItem('CHECK-BOX'))
        select.push(...selectedRowKeys)
        localStorage.removeItem('CHECK-BOX')
        localStorage.setItem('CHECK-BOX', JSON.stringify([...new Set(select)]))
      }
      this.selectedRowKeys1 = JSON.parse(localStorage.getItem('CHECK-BOX'))
    },
    // 点击关联税务目录
    handleAssociation (id) {
      // 查询按钮判断
      if (id) {
        this.cInvCode = id
      }
      this.visible = true
      this.loading1 = true
      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordList', {
          PageIndex: this.pagination1.current,
          PageRows: this.pagination1.pageSize,
          'SortField': 'TaxproductId',
          'SortType': 'desc',
          'Search': {
            'Keyword': this.cInvCode
          }
        })
        .then((resJson) => {
          this.loading1 = false
          this.beforeAssociation = resJson.Data
          const pagination = { ...this.pagination1 }
          pagination.total = resJson.Total
          this.pagination1 = pagination
        })
    },
    onSelect (record, selected, s) {
      this.selectedRowKeys1 = [record.Id]
      this.TaxList = s
      // let select = JSON.parse(localStorage.getItem('CHECK-BOX'));
      // if(selected){
      //     this.selectedRowKeys1.push(record.Id);
      // }else{
      //     //删除取消选择的
      //     select = select.filter(item => item != record.Id);
      //     this.selectedRowKeys1 = this.selectedRowKeys1.filter(item=>item != record.Id);
      // }
      // // 如果选择无数据，就创建一个新的加进去。
      // if (!JSON.parse(localStorage.getItem('CHECK-BOX'))) {
      //     localStorage.setItem('CHECK-BOX', JSON.stringify(this.selectedRowKeys1))
      // } else {
      //     //反则push
      //     select.push(...this.selectedRowKeys1);
      //     localStorage.removeItem('CHECK-BOX');
      //     localStorage.setItem('CHECK-BOX', JSON.stringify([...new Set(select)]))
      // }
      this.submitDisabled = this.selectedRowKeys1.length <= 0
    },
    onSelectAll (selected, selectedRows, changeRows) {
      const select = JSON.parse(localStorage.getItem('CHECK-BOX'))
      if (selected) {
        changeRows.forEach(item => {
          this.selectedRowKeys1.push(item.Id)
        })
      } else {
        // //删除取消选择的
        // select = select.filter(item => item != record.Id);
        changeRows.forEach(item => {
          select.forEach((item2, index) => {
            if (item2 == item.Id) {
              select.splice(index, 1)
            }
          })
        })
        this.selectedRowKeys1 = []
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('CHECK-BOX'))) {
        localStorage.setItem('CHECK-BOX', JSON.stringify(this.selectedRowKeys1))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys1)
        localStorage.removeItem('CHECK-BOX')
        localStorage.setItem('CHECK-BOX', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys1.length <= 0
    },
    // 关闭关联税务目录
    onClose () {
      this.visible = false
      this.pagination1.current = 1
    },
    
    // 导入
    handleImport () {
      this.visibleImport = true
    },
    downloadTemplate () {
      this.$http
        .post('/Cfg/cfg_compare_store/ExportToExcel', null, { responseType: 'blob' })
        .then((res) => {
          const url = URL.createObjectURL(res)
          const fileName = '仓库对照表模板'
          const aTag = document.createElement('a')
          aTag.download = fileName
          aTag.href = url
          aTag.click()
          URL.revokeObjectURL(aTag.href)
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 添加按钮
    handleAddS (add) {
      this.visiblees = true
      this.loading2 = true
      this.selectedRowKeys1 = []
      this.$http
        .post('MaterialManagement/TaxMaterials/GetDataList', {
          PageIndex: this.pagination2.current,
          PageRows: this.pagination2.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam2,
          ...this.filters2
        })
        .then((resJson) => {
          this.loading2 = false
          if (add) {
            localStorage.removeItem('CHECK-BOX')
          }
          this.association = resJson.Data
          this.association.forEach(item => {
            item.TM_TaxRate = item.TM_TaxRate + '%'
          })
          this.allData.push(...resJson.Data)
          this.allData = [...new Set(this.allData)]
          // 0否1是
          this.association.forEach(item => {
            item.TM_IsTax = item.TM_IsTax ? '是' : '否'
          })
          if (this.association) {
            const pagination = { ...this.pagination2 }
            pagination.total = resJson.Total
            this.pagination2 = pagination
          }
        })
    },
    // 关联税务目录确定
    associationOK () {
      if (!this.selectedRowKeys1) {
        this.$message.error('请选择税务目录!')
        return
      }
      console.log(this.TaxList)
      this.TaxValue = this.TaxList[0].Id
      this.setPrice = this.TaxList[0].TM_UnitPrice
      this.IsTax = this.TaxList[0].TM_IsTax == '是' ? 1 : 0
      this.TaxRate = this.TaxList[0].TM_TaxRate.replace('%', '')
      this.visiblees = false
      this.saveObj = this.TaxList[0]
      // console.log(this.allData)
      // let arr = this.allData.filter(item => item.Id==this.selectedRowKeys1[0]);
      // arr.forEach(item => { item.cInvCode = this.cInvCode });
      // this.$http
      //     .post('/MaterialManagement/TaxMaterialsRelation/AddTaxMaterialsRelationList', arr)
      //     .then((resJson) => {
      //         if (resJson.Success) {
      //             this.$message.success('关联成功')
      //             this.visiblees = false;
      //             // localStorage.removeItem('CHECK-BOX');
      //             // this.handleAssociation()
      //         } else {
      //             this.$message.error('关联失败')
      //         }
      //     })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleDelete (ids) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          thisObj.$http.post('/Cfg/cfg_compare_store/DeleteData', ids == 'all' ? this.selectedRowKeys : [ids]).then((resJson) => {
            resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-card-body {
  padding-bottom: 0px;
}
</style>